package jaux.tank.dao.utils;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Converter(autoApply = true)
@Component
public class JpaConverterJson implements AttributeConverter<Object, String> {

  private static final ObjectMapper objectMapper = new ObjectMapper();
  
  private static final Logger logger = LoggerFactory.getLogger(JpaConverterJson.class);

  @Override
  public String convertToDatabaseColumn(Object meta) {
		if (meta == null) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(meta);
		} catch (Exception ex) {
			logger.error("转换实体属性到json格式字符串失败", ex);
			return null;
		}
  }

  @Override
  public Object convertToEntityAttribute(String dbData) {
		if (StringUtils.isBlank(dbData)) {
			return null;
		}
		try {
			return objectMapper.readValue(dbData, Object.class);
		} catch (Exception ex) {
			logger.error("转换json格式字符串到实体属性失败", ex);
			return null;
		}
  }

}